<?php
/**
 * Model for a PHP Unit log.
 *
 * @category PhpCilux
 * @package  PhpCilux
 */

/**
 * Model for a PHP Unit log.
 *
 * @package PhpCilux
 */
class Model_Log_PhpUnit extends Model_Log_Abstract
{

    /**
     * Constructor.
     *
     * @param string $projectKey The project key.
     * @param string $buildKey   The build key.
     */
    public function __construct($projectKey, $buildKey)
    {
        parent::__construct($projectKey, $buildKey);

        $this->_logFilename = 'phpunit.txt';
    }

    /**
     * Get the status of the PHP Unit log.
     *
     * @return string
     */
    public function status()
    {
        $log        = $this->getContent();
        $lines      = explode("\n", $log);
        $totalLines = count($lines);

        $line = $lines[($totalLines - 2)];
        $pos  = stripos($line, '[2K');

        if ($pos !== false) {
            $line = substr($line, ($pos + 3));
        }

        if ('OK' == substr($line, 0, 2)) {
            return 'success';
        }

        return 'failed';
    }

    /**
     * Formating the log.
     *
     * @param string $content The log content which will be styled.
     *
     * @return string
     */
    public function format($content)
    {
        $lines = explode("\n", $content);

        $content = '<h4>PHPUnit</h4>';

        $totalLines = count($lines);

        while (list($key, $line) = each($lines)) {
            $line = rtrim($line);

            switch(true) {
                case 0 == $key:
                case '' == trim($line):
                case $key == ($totalLines - 1):
                    break;

                case stripos($line, '[2K') !== false:
                    $pos  = stripos($line, '[2K');
                    $line = substr($line, ($pos + 3));

                    if ('OK' === substr($line, 0, 2)) {
                        $content .= '<div class="success"><pre>' . $line . '</pre></div>';
                    } elseif ('FAILURES' == substr($line, 0, 8)) {
                        $content .= '<div class="failed"><pre>' . $line . '</pre></div>';
                    } else {
                        $content .= '<pre>' . $line . '</pre>';
                    }
                    break;

                default:
                    $content .= '<pre>' . $line . '</pre>';
                    break;
            }
        }

        $content .= '<br />';

        return $content;
    }

}